package br.com.roteador.component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@WebServlet(name="localizacaoServlet", urlPatterns={"/LocalizacaoServlet"}, 
	//asyncSupported=true, loadOnStartup=0)
public class LocalizacaoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/event-stream");
		response.setCharacterEncoding("UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST");
		response.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");
		request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
		AsyncContext aCtx = request.startAsync(request, response);
		aCtx.setTimeout(0);
		addListener(aCtx);
		ServletContext appScope = request.getServletContext();    
		Map<String, List<AsyncContext>> observadores = (Map<String, List<AsyncContext>>)appScope.getAttribute("observadores");
		if(observadores == null || observadores.isEmpty()){
			List<AsyncContext> watchers = new ArrayList<AsyncContext>();
	        watchers.add(aCtx);
	        observadores.put((String) "", watchers);
		} else {
			Iterator it = observadores.entrySet().iterator();
		    while (it.hasNext()) {
		        Map.Entry pairs = (Map.Entry)it.next();
		        List<AsyncContext> watchers = (List<AsyncContext>)pairs.getValue();
		        if(watchers == null || watchers.isEmpty()){
		        	watchers = new ArrayList<AsyncContext>();
		        	watchers.add(aCtx);
		        } else {
					watchers.add(aCtx);
		        }
		        observadores.put((String) pairs.getKey(), watchers);
		    }
		}
		
	    appScope.setAttribute("observadores", observadores);
	}
	
	private void addListener(AsyncContext ac){
		ac.addListener(new AsyncListener() {
       	 
            @Override
            public void onTimeout(AsyncEvent arg0) throws IOException {
                System.out.println("onTimeout...");            
            }
 
            @Override
            public void onStartAsync(AsyncEvent arg0) throws IOException {
                System.out.println("onStartAsync...");             
            }
 
            @Override
            public void onError(AsyncEvent arg0) throws IOException {
                System.out.println("onError...");          
            }
 
            @Override
            public void onComplete(AsyncEvent arg0) throws IOException {
                System.out.println("onComplete...");
            }
       });
	}

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
} 